<?php
/**
 * 微博评论
 * @author M2
 * @version 1.0
 * create Date 2013-04-27
 */
class CommentModel extends Model {
    var $tableName = 'weibo_comment';
    protected $mid;
    function _initialize() {
    	$this->mid = session('mid');
    }
    /**
     * 发布评论
     * @param array $data
     */
    function addcomment($data){
		 $data['comment_ip'] = get_client_ip();
         if( $id= $this->add( $data ) ){
         	 model('Weibo')->_removeWeiboCache($data['weibo_id']);
             M('Weibo')->where('weibo_id='.$data['weibo_id'])->setInc('comment');
             return $id;
         }else{
             return false;
         }
    	return true;
    }

	/**
	 * 发布评论同时发布一条微博
	 * @param int $uid 用户ID
	 * @param array $post
	 * @param boolean $api
	 */
    public function doaddcomment($uid, $post, $api=false){
        $data['uid']     = $uid;
        $data['reply_comment_id']   = intval($post['reply_comment_id']);
        $data['weibo_id']   = intval($post['weibo_id']);
        $data['content'] = common('Html')->text(common('Url')->getShort($post['content'],$GLOBALS['yl']['site']['length']));
        $data['content'] = preg_replace_callback('/((?:https?|ftp):\/\/(?:www\.)?(?:[a-zA-Z0-9][a-zA-Z0-9\-]*\.)?[a-zA-Z0-9][a-zA-Z0-9\-]*(?:\.[a-zA-Z0-9]+)+(?:\:[0-9]*)?(?:\/[^\x{2e80}-\x{9fff}\s<\'\"“”‘’]*)?)/u',common('Url')->getContentUrl, $data['content']);
        $data['ctime']   = time();
        $miniInfo = model('Weibo')->where('weibo_id='.$data['weibo_id'].' AND isdel=0')->find();
        if( $data['reply_comment_id'] ){
        	$replyInfo = $this->where('comment_id='.$data['reply_comment_id'].' AND isdel=0')->find();
        	$data['reply_uid'] = $replyInfo['uid'];
        }else{
        	$data['reply_uid'] = $miniInfo['uid'];
        	$notify['reply_type'] = 'weibo';
        }
        if ( $comment_id = $this->addcomment( $data ) ){
            if($data['uid'] == $data['reply_uid']){
                $this->setUserCredit($data['uid'],'add_comment');
            }
			//微博回复积分操作
			if($data['uid'] != $data['reply_uid']){
				$this->setUserCredit($data['uid'],'reply_comment');
			    $this->setUserCredit($data['reply_uid'],'replied_comment');
                $this->setUserCredit($data['reply_uid'],'is_commented');
			}
            $data['comment'] = $miniInfo['comment'] + 1;
            $return['data'] = $data;
            if (empty($post['imagemultiple'])){
            	$return['html'] = '<dl class="cmt-item" id="comment_list_c_'.$comment_id.'"><dt>
	            <a href="'.URL('home/Space/index',array('uid'=>$this->mid)).'" class="avatar-s" target="_blank">'.common('Url')->getUserFace($uid,'s',42,42).'</a>
	            </dt><dd>
	            <p><a href="#">'.common('Url')->getUserSpace($uid, 'null', '_blank', '').'</a>：'.common('String')->formatComment( $data['content'] ,true ).'(刚刚)</p>
	            <div class="cmt-handle">
	            <a href="javascript:void(0)" onclick="ui.confirm(this,'.L('youSureWantToDeleteThisComment').')" callback="delComment('.$comment_id.')">'.L('del').'</a>
	            <a href="javascript:void(0)" onclick="reply(\''.common('String')->getUserName($uid).'\','.$data['weibo_id'].')">'.L('reply').'</a>
	            </div></dd></dl>';
            }else {
            	$return['html'] = '<div class="cmt-item" id="multiple_cmt-item_'.$comment_id.'">
                                <p><a href="'.URL('home/Space/index',array('uid'=>$this->mid)).'" target="_blank">'.common('String')->getUserName($uid).'</a>：'.common('String')->formatComment( $data['content'] ,true ).'(刚刚)</p>
                                <div class="cmt-handle">
									<a href="javascript:void(0)" onclick="doDelComment('.$comment_id.')">'.L('del').'</a>
									<a href="javascript:void(0)" onclick="reply(\''.common('String')->getUserName($uid).'\','.$data['weibo_id'].')">'.L('reply').'</a>
                                </div></div>';
            }

            if( $post['transpond'] != 0 ){
            	if($miniInfo['transpond_id']!=0){
            		$transpondData['content']     	   = $data['content'].($data['reply_comment_id']?(" //@".common('String')->getUserName($replyInfo['uid'])." :".$replyInfo['content']):'')." //@".common('String')->getUserName($miniInfo['uid']).":".$miniInfo['content'];
            		$transpondData['transpond_id']     = $miniInfo['transpond_id'];
            		$transpondInfo = M('weibo')->where('weibo_id='.$miniInfo['transpond_id'].' AND isdel=0')->find();
            		$transpondData['transpond_uid']     = $transpondInfo['uid'];
            	}else{
            		$transpondData['content']          = $data['content'].($data['reply_comment_id']?(" //@".common('String')->getUserName($replyInfo['uid'])." :".$replyInfo['content']):'');
            		$transpondData['transpond_id']     = $miniInfo['weibo_id'];
            		$transpondData['transpond_uid']     = $miniInfo['uid'];
                }
            	$id = model('Weibo')->doSaveWeibo($uid,$transpondData,$post['from']);
			    if ($id) {  //当转发的微博uid 与 回复人的uid不一致时发布@到我
			    	if($transpondData['transpond_uid'] != $data['reply_uid']){
			    		model('Weibo')->notifyToAtme($uid, $id, $transpondData['content'], $transpondData['transpond_uid']);
			    	}else{
			    		model('Weibo')->notifyToAtme($uid, $id, $transpondData['content'], $transpondData['transpond_uid'],false);
			    	}
			    }
            }
            //添加统计
            if($api){
            	if($data['reply_uid'] != $miniInfo['uid']){
            		model('UserCount')->addCount($miniInfo['uid'],'comment');
            	}
            }else{
            	model('UserCount')->addCount($data['reply_uid'],'comment');
            	if($data['reply_uid'] != $miniInfo['uid']){
            		model('UserCount')->addCount($miniInfo['uid'],'comment');
            	}
            }
            if($api){
            	return true;
            }else{
            	return json_encode($return);
            }
        }else{
        	return '0';
        }
    }
    /**
     * 获取评论
     * @param int $id 微博ID
     * @param int $limit 显示的条数
     * @param string $order 排序
     */
    function getComment( $id, $limit = 10, $order = 'comment_id DESC' ){
    	return $this->where("weibo_id={$id} AND isdel=0")->order($order)->findPage($limit);
    }

	/**
	 * 发出的评论
	 * @param string $type 评论类型
	 * @param string $person
	 * @param int $uid 用户ID
	 */
    function getCommentList($type='receive',$person='all',$uid) {
    	if ($type == 'send') { // 发出的评论
	    	if ($person == 'follow') {
	    		$map = "reply_uid IN (SELECT fid FROM {$this->tablePrefix}weibo_follow where uid={$uid})";
	    	}else if ($person=='other'){
	    		$map = "reply_uid NOT IN (SELECT fid FROM {$this->tablePrefix}weibo_follow where uid={$uid})";
	    	}else{
	    		$map = '1=1';
	    	}
	    	$list = $this->where($map." AND uid=".$uid." AND reply_uid<>$uid".' AND isdel=0')->order('comment_id DESC')->findPage(10);
        } else { // 收到的评论
    		$list = $this->field('c.*')
    					 ->table("{$this->tablePrefix}weibo_comment AS c LEFT JOIN {$this->tablePrefix}weibo AS w ON c.weibo_id=w.weibo_id")
    					 ->where("c.isdel=0 AND w.isdel=0 AND (c.reply_uid={$uid} OR w.uid={$uid} ) and c.uid != {$uid}")
    					 ->order('c.comment_id DESC')
    					 ->findPage(10);
    	}
    	// 缓存被评论的微博, 被回复的评论, 评论的发表人, 被回复的用户
    	$ids = common('Array')->getSubByKeyArray($list['data'], 'comment_id,reply_comment_id,weibo_id,uid,reply_uid');
    	model('Weibo')->setWeiboObjectCache($ids['weibo_id']);
    	model('User')->setUserObjectCache(array_merge($ids['uid'], $ids['reply_uid']));
    	$this->setCommentObjectCache(array_merge($ids['comment_id'], $ids['reply_comment_id']));
        foreach ($list['data'] as $key => $value) {
    		$list['data'][$key]['mini'] = model('Weibo')->getOneLocation($value['weibo_id'], '', false);
    		if( !$value['reply_comment_id'] ){
    			$list['data'][$key]['reply_uid']  = $list['data'][$key]['mini']['uid'];
    			$list['data'][$key]['ismini'] = true;
    		}else {
    			$list['data'][$key]['comment'] = $this->getCommentDetail($value['reply_comment_id']);
    		}
    	}
    	return $list;
    }

    /**
     * 删除评论
     * @param int $id 评论ID
     * @param int $uid 用户ID
     */
    function deleteComments($id,$uid){
    	$pMiniBlog = model('Weibo');
       	$info = $this->where('comment_id='.$id)->find();
       	$webInfo = $pMiniBlog->where('weibo_id='.$info['weibo_id'])->field('uid,comment')->find();
    	if( $info['uid']==$uid || $webInfo['uid']==$uid || $GLOBALS['yl']['isSystemAdmin']){
    		if($info['isdel'] == 0 && $this->where('comment_id='.$id.' AND isdel=0')->setField('isdel',1)){
    			$pMiniBlog->where('weibo_id='.$info['weibo_id'])->setDec('comment');
    			if($info['uid'] != $info['reply_uid']){//删除自己给自己的评论，不扣积分
					$this->setUserCredit($info['uid'],'delete_weibo_comment');
					$this->setUserCredit($info['reply_uid'],'delete_weibo_comment');
    			}
    		}elseif($info['isdel'] == 1){
    			$this->where('comment_id='.$id.' AND isdel=1')->delete();
    		}
            $pMiniBlog->_removeWeiboCache($info['weibo_id']);
    		$r['boolen'] = 1;
    		$r['message'] = L('del_success');
    		$r['count']   = intval( $webInfo['comment'] -1 );
    	}else{
    		$r['boolen'] = 0;
    		$r['message'] = L('del_failed');
    	}
    	return $r;
    }

	/**
	 * 批量删除评论
	 * @param int $id 评论ID
     * @param int $uid 用户ID
	 */
    function deleteMuleComments($id,$uid) {
    	$pMiniBlog = model('Weibo');
    	$id = is_array($id) ? $id : explode(',', $id);
    	foreach ($id as $k=>$v){
    		$info = $this->where('comment_id='.$v)->find();
    		$webInfo = $pMiniBlog->where('weibo_id='.$info['weibo_id'])->field('uid')->find();
	    	if( $info['uid']==$uid || $webInfo['uid']==$uid ){
	    		if($info['isdel'] == 0 && $this->where('comment_id='.$v.' AND isdel=0')->setField('isdel',1)){
	    			$pMiniBlog->setDec('comment', 'weibo_id='.$info['weibo_id'] );
	    			if($info['uid'] != $info['reply_uid']){//删除自己给自己的评论，不扣积分
						$this->setUserCredit($info['uid'],'delete_weibo_comment');
						$this->setUserCredit($info['reply_uid'],'delete_weibo_comment');
	    			}
	    		}elseif($info['isdel'] == 1){
	    			$this->where('comment_id='.$v.' AND isdel=1')->delete();
	    		}
                $pMiniBlog->_removeWeiboCache($info['weibo_id']);
	    	}
    	}
    	return true;
    }

    /**
     * 获取详细评论
     * @param int $comment_id 评论ID
     */
    public function getCommentDetail($comment_id) {
    	$cache_id = 'weibo_comment_' . $comment_id;
    	if (($res = S($cache_id)) === false) {
    		$res = $this->where("`comment_id` = '{$comment_id}' AND `isdel` = 0")->find();
    		S($cache_id, $res);
    	}
    	return $res;
    }

    /**
     * 缓存微博评论
     * 缓存的key的格式为: weibo_comment_微博评论ID.
     * @param array $comment_list 微博评论ID列表, 或者微博评论详情列表. 如果为微博评论ID列表时, 本方法会首先获取微博评论详情列表, 然后缓存.
     */
    public function setCommentObjectCache(array $comment_list) {
    	if (!is_array($comment_list[0]) && !is_numeric($comment_list[0]))
    		return false;
    	if (is_numeric($comment_list[0])) { // 给定的是weibo_comment_id的列表. 查询weibo_comment详情
	    	$map['comment_id'] = array('in', $comment_list);
	    	$map['isdel']      = 0;
	    	$comment_list      = $this->where($map)->select();
    	}
    	foreach ($comment_list as $v)
	   		S("weibo_comment_{$v['comment_id']}", $v);
	   	return $comment_list;
    }

	/**
	 * 设置用户积分
	 * @param int $uid 用户ID
	 * @param string $creditType 积分类型
	 */
	private function setUserCredit($uid,$creditType){
		$credit_Type = M('credit_type')->select();
		$creditValue = M('credit_setting')->where("name='".$creditType."'")->select();
		$creditUser = M('credit_user')->where("uid=".$uid)->select();
		$strSql="";
		if(count($creditUser)>0){
			$db_prefix  = C('DB_PREFIX');
			$strSql="UPDATE ".$db_prefix."credit_user SET ";
			$link="";
			foreach($credit_Type as $v){
				$strSql=$strSql.$link.$v['name']."=ifnull(".$v['name'].",0)+ifnull(".$creditValue[0][$v['name']].",0)" ;
				$link=",";
			}
			$strSql=$strSql." where uid=".$uid;
			$res=M('credit_user')->query($strSql);
		}else {
			foreach($credit_Type as $v){
				$value[$v['name']] = intval($creditValue[0][$v['name']]);
			}
			$value["uid"] = $uid;
			$res = M('credit_user')->data($value)->add();
		}
	}
}
